package com.ly.emp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ly.common.core.bean.R;
import com.ly.emp.bean.dto.DynamicTableDTO;
import com.ly.emp.bean.vo.DynamicTableHeadAndChildrenListVO;
import com.ly.emp.bean.vo.DynamicTableHeadListAndDatasVO;
import com.ly.emp.bean.vo.DynamicTableHeadListVo;
import com.ly.emp.entity.*;
import com.ly.emp.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;

import static java.util.stream.Collectors.groupingBy;

/**
 * 实现类-动态表头
 *
 * @author luoyun
 * @Date: 2023-05-18
 */
@Service
@RequiredArgsConstructor
public class DynamicTableServiceImpl implements DynamicTableService {

    private final IHubTeamQuotaOrgService hubTeamQuotaOrgService;
    private final IHubTeamCaseOrgService hubTeamCaseOrgService;
    private final IHubTeamXsSetService hubTeamXsSetService;
    private final IHubTeamXsItemService hubTeamXsItemService;
    private final IHubTeamWorkService hubTeamWorkService;
    private final IHubTeamTemplateService hubTeamTemplateService;
    private final IHubTeamTemplateConfigService hubTeamTemplateConfigService;
    private final IHubTeamEvaluateIndexService hubTeamEvaluateIndexService;

    @Override
    public R<List<DynamicTableHeadListVo>> getQuotaFactorOrgHeader(DynamicTableDTO dto) {
        HubTeamQuotaOrg entity = BeanUtil.toBean(dto, HubTeamQuotaOrg.class);
        R r = hubTeamQuotaOrgService.getList(entity);
        List<HubTeamQuotaOrg> list = (List<HubTeamQuotaOrg>) r.getResult();
        List<DynamicTableHeadListVo> vos = new ArrayList<>();
        if (CollUtil.isNotEmpty(list)) {
            list.stream().forEach(n -> {
                DynamicTableHeadListVo vo = new DynamicTableHeadListVo();
                vo.setHeadCode(n.getSaveCode());
                vo.setHeadName(n.getFactorName());
                vos.add(vo);
            });
        }
        return R.ok(vos);
    }

    @Override
    public R<List<DynamicTableHeadListAndDatasVO>> getTeamResultOrderXsHeader(DynamicTableDTO dto) {
        List<HubTeamXsSet> list = hubTeamXsSetService.list(
                new LambdaQueryWrapper<HubTeamXsSet>()
                        .eq(HubTeamXsSet::getOrgCode, dto.getOrgCode())
                        .orderByAsc(HubTeamXsSet::getDisplayOrder)
        );
        List<DynamicTableHeadListAndDatasVO> vos = new ArrayList<>();
        if (CollUtil.isNotEmpty(list)) {
            list.stream().forEach(n -> {
                DynamicTableHeadListAndDatasVO<HubTeamXsItem> vo = new DynamicTableHeadListAndDatasVO();
                String xsCode = n.getXsCode();
                vo.setHeadCode(xsCode);
                vo.setHeadName(n.getXsName());
                if (StrUtil.isNotBlank(xsCode)) {
                    // 系数下拉框数据
                    List<HubTeamXsItem> xsDetailsList = hubTeamXsItemService.list(
                            new LambdaQueryWrapper<HubTeamXsItem>()
                                    .eq(HubTeamXsItem::getOrgCode, dto.getOrgCode())
                                    .eq(HubTeamXsItem::getXsCode, xsCode)
                                    .orderByAsc(HubTeamXsItem::getDisplayOrder)
                    );
                    vo.setDatas(xsDetailsList);
                }
                vos.add(vo);
            });
        }
        return R.ok(vos);
    }

    @Override
    public R<List<DynamicTableHeadListVo>> getTeamResultHeader(DynamicTableDTO dto) {
        HubTeamCaseOrg hubTeamCaseOrg = new HubTeamCaseOrg();
        hubTeamCaseOrg.setOrgCode(dto.getOrgCode());
        hubTeamCaseOrg.setCaseStatus("true");
        R r = hubTeamCaseOrgService.getList(hubTeamCaseOrg);
        List<HubTeamCaseOrg> list = (List<HubTeamCaseOrg>) r.getResult();
        List<DynamicTableHeadListVo> vos = new ArrayList<>();
        if (CollUtil.isNotEmpty(list)) {
            list.stream().forEach(n -> {
                DynamicTableHeadListVo vo = new DynamicTableHeadListVo();
                vo.setHeadCode(n.getSaveCode());
                vo.setHeadName(StrUtil.isNotBlank(n.getNickName()) ? n.getNickName() : n.getCaseName());
                vos.add(vo);
            });
        }
        return R.ok(vos);
    }

    @Override
    public R<List<DynamicTableHeadListVo>> getTemplateConfigHeader(DynamicTableDTO dto) {
        // 判断是否以及添加对应的类型
        HubTeamTemplate hubTeamTemplate = hubTeamTemplateService.getOne(
                new LambdaQueryWrapper<HubTeamTemplate>()
                        .eq(HubTeamTemplate::getOrgCode, dto.getOrgCode())
                        .eq(HubTeamTemplate::getType, dto.getType())
        );
        if (hubTeamTemplate == null) {
            return R.fail("请先配置对应模板");
        }
        // 获取综合评价模板配置
        List<HubTeamTemplateConfig> list = hubTeamTemplateConfigService.list(
                new LambdaQueryWrapper<HubTeamTemplateConfig>()
                        .eq(HubTeamTemplateConfig::getTemplateCode, hubTeamTemplate.getTemplateCode())
                        .eq(HubTeamTemplateConfig::getIsOpen, "true")
                        .orderByAsc(HubTeamTemplateConfig::getSaveCode)
        );
        // 表头字段赋值
        List<DynamicTableHeadListVo> vos = new ArrayList<>();
        if (CollUtil.isNotEmpty(list)) {
            list.stream().forEach(n -> {
                DynamicTableHeadListVo vo = new DynamicTableHeadListVo();
                vo.setHeadCode(n.getSaveCode());
                vo.setHeadName(n.getSaveName());
                vos.add(vo);
            });
        }
        return R.ok(vos);
    }

    @Override
    public R<List<DynamicTableHeadAndChildrenListVO>> getResultEvaluateHeader(DynamicTableDTO dto) {
        // 类型 (1：月度  2：季度 3：年度 )
        String type = dto.getType();
        if (type == null) {
            return R.fail("模板类型不能为空");
        }
        // 判断是否以及添加对应的类型
        HubTeamTemplate hubTeamTemplate = hubTeamTemplateService.getOne(
                new LambdaQueryWrapper<HubTeamTemplate>()
                        .eq(HubTeamTemplate::getOrgCode, dto.getOrgCode())
                        .eq(HubTeamTemplate::getType, type)
        );
        if (hubTeamTemplate == null) {
            return R.fail("请先配置对应模板");
        }
        // 获取对应班组月度评价的模板
        List<HubTeamEvaluateIndex> list = hubTeamEvaluateIndexService.list(
                new LambdaQueryWrapper<HubTeamEvaluateIndex>()
                        .eq(HubTeamEvaluateIndex::getOrgCode, dto.getOrgCode())
                        .eq(HubTeamEvaluateIndex::getTemplateCode, hubTeamTemplate.getTemplateCode())
                        .eq(HubTeamEvaluateIndex::getPeriodCode, dto.getPeriodCode())
                        .orderByAsc(HubTeamEvaluateIndex::getDisplayOrder)
        );
        // 封装动态表头
        List<DynamicTableHeadAndChildrenListVO> vos = new ArrayList<>();
        System.out.println("全部的值为：" + list.size());
        if (CollUtil.isNotEmpty(list)) {
            IntStream.range(0, list.size()).forEach(i -> {
                DynamicTableHeadAndChildrenListVO vo = new DynamicTableHeadAndChildrenListVO();
                vo.setHeadName(list.get(i).getIndexName());
                vo.setValue(list.get(i).getFactorWeight());// 权重值
                // 多级表头，目前只处理二级的情况
                vo.setChildren(Arrays.asList(new DynamicTableHeadAndChildrenListVO[]{
                        new DynamicTableHeadAndChildrenListVO("weight" + (i + 1), "权重",list.get(i).getFactorWeight()),
                        new DynamicTableHeadAndChildrenListVO("score" + (i + 1), "评分",null),
                        new DynamicTableHeadAndChildrenListVO("scoreDesc" + (i + 1), "评分说明",null)
                }));
                vos.add(vo);
            });
        }
        return R.ok(vos);
    }

    @Override
    public R<List<DynamicTableHeadAndChildrenListVO>> getResultOrderForTwoDimensionalHeader(DynamicTableDTO dto) {
        // 获取对应班组全部类型
        HubTeamWork entity = new HubTeamWork();
        entity.setOrgCode(dto.getOrgCode());
        entity.setPeriodCode(dto.getPeriodCode().substring(0, 4));
        R r = hubTeamWorkService.getList(entity);
        List<HubTeamWork> list = (List<HubTeamWork>) r.getResult();
        // 封装动态表头
        List<DynamicTableHeadAndChildrenListVO> vos = new ArrayList<>();
        if (CollUtil.isNotEmpty(list)) {
            Map<String, List<HubTeamWork>> map =
                    list.stream().filter(n -> StrUtil.isNotBlank(n.getWorkTypeCode())).collect(groupingBy(HubTeamWork::getWorkTypeName));
            if (map != null) {
                map.forEach((k, v) -> {
                    DynamicTableHeadAndChildrenListVO vo = new DynamicTableHeadAndChildrenListVO();
                    vo.setHeadName(k);
                    wrapperTwoDimensionalHeader(vo, v);
                    vos.add(vo);
                });
            }
        }
        return R.ok(vos);
    }

    public void wrapperTwoDimensionalHeader(DynamicTableHeadAndChildrenListVO vo, List<HubTeamWork> list) {
        List<DynamicTableHeadAndChildrenListVO> vos = new ArrayList<>();
        if (CollUtil.isNotEmpty(list)) {
            list.stream().forEach(n -> {
                DynamicTableHeadAndChildrenListVO vo1 = new DynamicTableHeadAndChildrenListVO(n.getWorkItemCode(), n.getWorkItemName(),null);
                vos.add(vo1);
            });
            vo.setChildren(vos);
        }
    }
}